package com.osell.selection.ui.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.da.lon.wang.xlg.R;
import com.osell.selection.data.entity.PageResult;
import com.osell.selection.data.network.RestAPI;
import com.osell.selection.data.network.entity.Product;
import com.osell.selection.ui.base.RecyclerFragment;
import com.osell.selection.ui.base.SlimAdapter;
import com.osell.selection.ui.common.WebViewActivity;
import com.osell.selection.ui.product.ProductDetailActivity;
import com.osell.selection.util.DimenUtils;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class HomeProductsFragment extends RecyclerFragment<Product> {

    private SlimAdapter mAdapter;

    private String mCategoryId;

    public static HomeProductsFragment newInstance(String categoryId) {
        HomeProductsFragment fragment = new HomeProductsFragment();
        Bundle args = new Bundle();
        args.putString("category_id", categoryId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mCategoryId = getArguments().getString("category_id");
        }
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_home_products;
    }

    @Override
    public RecyclerView.Adapter onCreateAdapter(List<Product> data) {
        mAdapter = SlimAdapter.create()
                .register(new SlimAdapter.SlimInjector<Product.AdProduct>() {
                    @Override
                    public int onGetLayoutResource() {
                        return R.layout.home_product_ad_item;
                    }

                    @Override
                    public void onInit(final SlimAdapter.SlimViewHolder<Product.AdProduct> viewHolder) {
                        viewHolder.clicked(v -> {
                            if (viewHolder.itemData.webFlag == 1) {
                                v.getContext().startActivity(new Intent(v.getContext(), WebViewActivity.class)
                                        .putExtra("hide_top_bar", true)
                                        .putExtra("url", viewHolder.itemData.webUrl));
                            } else {
                                v.getContext().startActivity(new Intent(v.getContext(), ProductDetailActivity.class)
                                        .putExtra("product_number", viewHolder.itemData.number));
                            }
                        });
                    }

                    @Override
                    public void onBind(Product.AdProduct data, SlimAdapter.SlimViewHolder<Product.AdProduct> viewHolder) {
                        Glide.with(viewHolder.itemView.getContext())
                                .load(data.posterUrl)
                                .placeholder(R.drawable.inset_place_holder_logo)
                                .into((ImageView) viewHolder.id(R.id.iv_product_ad_image));
                        viewHolder.text(R.id.tv_product_info, data.storeName);
                    }
                })
                .register(new SlimAdapter.SlimInjector<Product.VideoProduct>() {
                    @Override
                    public int onGetLayoutResource() {
                        return R.layout.home_product_video_item;
                    }

                    @Override
                    public void onInit(final SlimAdapter.SlimViewHolder<Product.VideoProduct> viewHolder) {
                        viewHolder.clicked(v -> {
                            if (viewHolder.itemData.webFlag == 1) {
                                v.getContext().startActivity(new Intent(v.getContext(), WebViewActivity.class)
                                        .putExtra("hide_top_bar", true)
                                        .putExtra("url", viewHolder.itemData.webUrl));
                            } else {
                                v.getContext().startActivity(new Intent(v.getContext(), ProductDetailActivity.class)
                                        .putExtra("product_number", viewHolder.itemData.number));
                            }
                        });
                    }

                    @Override
                    public void onBind(Product.VideoProduct data, SlimAdapter.SlimViewHolder<Product.VideoProduct> viewHolder) {
                        Glide.with(viewHolder.itemView.getContext())
                                .load(data.imageUrl)
                                .placeholder(R.drawable.inset_place_holder_logo)
                                .into((ImageView) viewHolder.id(R.id.iv_product_video_thumbnail));
                        viewHolder.text(R.id.tv_product_name, data.name)
                                .text(R.id.tv_product_info, data.storeName);
                    }
                })
                .register(new SlimAdapter.SlimInjector<Product.OneProduct>() {
                    @Override
                    public int onGetLayoutResource() {
                        return R.layout.home_product_one_item;
                    }

                    @Override
                    public void onInit(final SlimAdapter.SlimViewHolder<Product.OneProduct> viewHolder) {
                        viewHolder.clicked(v -> {
                            if (viewHolder.itemData.webFlag == 1) {
                                v.getContext().startActivity(new Intent(v.getContext(), WebViewActivity.class)
                                        .putExtra("hide_top_bar", true)
                                        .putExtra("url", viewHolder.itemData.webUrl));
                            } else {
                                v.getContext().startActivity(new Intent(v.getContext(), ProductDetailActivity.class)
                                        .putExtra("product_number", viewHolder.itemData.number));
                            }
                        });
                    }

                    @Override
                    public void onBind(Product.OneProduct data, SlimAdapter.SlimViewHolder<Product.OneProduct> viewHolder) {
                        viewHolder.text(R.id.tv_product_name, data.name)
                                .text(R.id.tv_product_info, data.storeName)
                                .text(R.id.tv_product_sub_title, data.subTitle);
                        Glide.with(viewHolder.itemView.getContext())
                                .load(data.imageUrl)
                                .placeholder(R.drawable.inset_place_holder_logo)
                                .into((ImageView) viewHolder.id(R.id.iv_product_image));
                    }
                })
                .register(new SlimAdapter.SlimInjector<Product.MoreProduct>() {
                    @Override
                    public int onGetLayoutResource() {
                        return R.layout.home_product_more_item;
                    }

                    @Override
                    public void onInit(final SlimAdapter.SlimViewHolder<Product.MoreProduct> viewHolder) {
                        viewHolder.clicked(v -> {
                            if (viewHolder.itemData.webFlag == 1) {
                                v.getContext().startActivity(new Intent(v.getContext(), WebViewActivity.class)
                                        .putExtra("hide_top_bar", true)
                                        .putExtra("url", viewHolder.itemData.webUrl));
                            } else {
                                v.getContext().startActivity(new Intent(v.getContext(), ProductDetailActivity.class)
                                        .putExtra("product_number", viewHolder.itemData.number));
                            }
                        });
                    }

                    @Override
                    public void onBind(Product.MoreProduct data, SlimAdapter.SlimViewHolder<Product.MoreProduct> viewHolder) {
                        Context context = viewHolder.itemView.getContext();
                        String[] ar = data.jpgUrl.split(",");
                        if (ar.length > 0) {
                            Glide.with(context)
                                    .load(ar[0])
                                    .placeholder(R.drawable.inset_place_holder_logo)
                                    .into((ImageView) viewHolder.id(R.id.iv_product_image_1));
                        }
                        if (ar.length > 1) {
                            Glide.with(context)
                                    .load(ar[1])
                                    .placeholder(R.drawable.inset_place_holder_logo)
                                    .into((ImageView) viewHolder.id(R.id.iv_product_image_2));
                        }
                        if (ar.length > 2) {
                            Glide.with(context)
                                    .load(ar[2])
                                    .placeholder(R.drawable.inset_place_holder_logo)
                                    .into((ImageView) viewHolder.id(R.id.iv_product_image_3));
                        }
                        viewHolder.text(R.id.tv_product_name, data.name)
                                .text(R.id.tv_product_info, data.storeName);
                    }
                })
                .enableDiff();
        return mAdapter;
    }

    @Override
    public Observable<PageResult<Product>> onCreatePageObservable(final int currentPage) {
        return RestAPI.getInstance().oSellService()
                .getCategoriesProducts(21, mCategoryId, currentPage)
                .map(homeInfoResponseData -> {
                    PageResult<Product> result = new PageResult<>();
                    result.page_number = currentPage;
                    result.page_size = 10;
                    result.total_pages = homeInfoResponseData.data.products.size() < result.page_size ? currentPage : Integer.MAX_VALUE;
                    result.elements = new ArrayList<>();
                    for (Product product : homeInfoResponseData.data.products) {
                        if (TextUtils.equals(product.type, "ad")) {
                            result.elements.add(Product.AdProduct.convertFrom(product));
                        } else if (TextUtils.equals(product.type, "video")) {
                            result.elements.add(Product.VideoProduct.convertFrom(product));
                        } else if (TextUtils.equals(product.type, "product_one")) {
                            result.elements.add(Product.OneProduct.convertFrom(product));
                        } else if (TextUtils.equals(product.type, "product_more")) {
                            result.elements.add(Product.MoreProduct.convertFrom(product));
                        }
                    }
                    result.total_elements = result.elements.size();
                    return result;
                })
                .toObservable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .cache();
    }

    @Override
    public void notifyDataChanged(List<Product> data) {
        mAdapter.updateData(data);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        swipe_refresh_layout.setColorSchemeResources(R.color.colorPrimary);

        recycler_view.setLayoutManager(new LinearLayoutManager(view.getContext()));
        recycler_view.addItemDecoration(new HorizontalDividerItemDecoration.Builder(recycler_view.getContext())
                .colorResId(R.color.colorDivider)
                .size((int) DimenUtils.dipToPixels(8, recycler_view.getContext()))
                .build());
        super.onViewCreated(view, savedInstanceState);
    }
}
